package com.sens.alipay.utils;

import android.content.Context;

import com.sens.common.ApplicationUtil;
import com.sens.common.Base64;
import com.sens.exception.PermissionException;

import de.robv.android.xposed.XposedHelpers;

public class AlipayUtils {
    private static final String packageName = new String(Base64.decode("Y29tLmVnLmFuZHJvaWQuQWxpcGF5R3Bob25l"));
    private static final String appPackageName = new String(Base64.decode("Y29tLmFsaXBheS5tb2JpbGU"));

    /**
     * 检测是否安装支付宝
     */
    public static boolean checkInstalled(Context context) {
        return ApplicationUtil.checkInstalled(context, packageName);
    }

    /**
     * 判断应用是否已经启动
     */
    public static boolean isRunning(Context context) throws PermissionException {
        return ApplicationUtil.isRunning(context, packageName, appPackageName);
    }

    /**
     * 启动支付宝
     */
    public static void startAlipay(Context context) {
        ApplicationUtil.startApp(context, packageName);
    }

    public static String getCookieStr(ClassLoader classLoader) throws Exception {
        // 获得cookieStr
        XposedHelpers.callStaticMethod(XposedHelpers.findClass("com.alipay.mobile.common.transportext.biz.appevent.AmnetUserInfo", classLoader), "getSessionid");
        Context context = (Context) XposedHelpers.callStaticMethod(XposedHelpers.findClass("com.alipay.mobile.common.transportext.biz.shared.ExtTransportEnv", classLoader), "getAppContext");
        if (context != null) {
            Object readSettingServerUrl = XposedHelpers.callStaticMethod(XposedHelpers.findClass("com.alipay.mobile.common.helper.ReadSettingServerUrl", classLoader), "getInstance");
            if (readSettingServerUrl != null) {
                String gWFURL = ".alipay.com";
                return (String) XposedHelpers.callStaticMethod(XposedHelpers.findClass("com.alipay.mobile.common.transport.http.GwCookieCacheHelper", classLoader), "getCookie", gWFURL);
            } else throw new Exception("readSettingServerUrl为空");
        } else throw new Exception("context为空");
    }

    public static String getUserId(ClassLoader classLoader) {
        Class<?> AlipayApplication = XposedHelpers.findClass("com.alipay.mobile.framework.AlipayApplication", classLoader);
        Class<?> socialSdkContactService = XposedHelpers.findClass("com.alipay.mobile.personalbase.service.SocialSdkContactService", classLoader);
        Object instace = XposedHelpers.callStaticMethod(AlipayApplication, "getInstance");
        Object applicationContext = XposedHelpers.callMethod(instace, "getMicroApplicationContext");
        Object service = XposedHelpers.callMethod(applicationContext, "findServiceByInterface", socialSdkContactService.getName());
        Object accountInfo = XposedHelpers.callMethod(service, "getMyAccountInfoModelByLocal");
        if (accountInfo != null) {
            return XposedHelpers.getObjectField(accountInfo, "userId").toString();
        } else return null;
    }
}
